import datetime

import pathway as pw
from datetime import date
from typing import Dict, Any, Optional

from application.db.mysql_db.info.ResourceInformationList import ResourceInformationList


class ResourceInformationListSchema(pw.Schema):
    information_id: str
    source_id: str
    information_name: Dict[str, Any]
    information_description: Optional[Dict[str, Any]] = pw.column_definition(default_value={})
    original_language: str = pw.column_definition(default_value="")
    cover: Optional[Dict[str, Any]] = pw.column_definition(default_value={})
    original_link: str = pw.column_definition(default_value="")
    publish_date: str = pw.column_definition(default_value="")
    metadata: Optional[Dict[str, Any]] = pw.column_definition(default_value={})
    review_user: int = pw.column_definition(default_value=0)
    collection_method: str = pw.column_definition(default_value="")
    manual_review_status: str = pw.column_definition(default_value="")
    machine_review_status: str = pw.column_definition(default_value="")
    is_del: int = pw.column_definition(default_value=0)


class ResourceInformationListRead(pw.io.python.ConnectorSubject):
    def run(self):
        select_list = ResourceInformationList.select().dicts()
        for doc in select_list:
            doc = self.transform(doc)
            self.next(**doc)

    def transform(self, transform_data):
        transform_data = {k: v for k, v in transform_data.items()
                          if v is not None and v != {}}
        if transform_data.get('publish_date'):
            # 处理publish_date可能已经是字符串的情况
            if isinstance(transform_data['publish_date'], (date, datetime.datetime)):
                transform_data['publish_date'] = transform_data['publish_date'].strftime("%Y-%m-%d")
            # 如果已经是字符串，则不需要转换
        return transform_data